﻿using elFinder.NetCore;
using elFinder.NetCore.Drivers.FileSystem;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using PlatformNetCore.Common;
using PlatformNetCore.Common.Helper;
using PlatformNetCore.Common.Utility;

namespace PlatformNetCore.Web.Controllers
{
    [Route("el-finder/file-system")]
    public class FileSystemController : Controller
    {
        IPathProvider pathProvider;
        public FileSystemController(IPathProvider _pathProvider)
        {
            pathProvider = _pathProvider;
        }
        
        [Route("connector")]
        public async Task<IActionResult> Connector()
        {
            try
            {
                var connector = GetConnector();
                return await connector.ProcessAsync(Request);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }

        [Route("thumb/{hash}")]
        public async Task<IActionResult> Thumbs(string hash)
        {
            try
            {
                var connector = GetConnector();
                return await connector.GetThumbnailAsync(HttpContext.Request, HttpContext.Response, hash);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }

        private Connector GetConnector()
        {
            try
            {
                var driver = new FileSystemDriver();

                string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
                var uri = new Uri(absoluteUrl);

                var root = new RootVolume(
                    pathProvider.MapPath("\\wwwroot\\uploads"),
                    $"http://{uri.Authority}/uploads/",
                    $"http://{uri.Authority}/el-finder/file-system/thumb/")
                {
                    //IsReadOnly = !User.IsInRole("Administrators")
                    IsReadOnly = false, // Can be readonly according to user's membership permission
                    IsLocked = false, // If locked, files and directories cannot be deleted, renamed or moved
                    Alias = "uploads", // Beautiful name given to the root/home folder
                                       //MaxUploadSizeInKb = 2048, // Limit imposed to user uploaded file <= 2048 KB
                                       //LockedFolders = new List<string>(new string[] { "Folder1" })
                };

                driver.AddRoot(root);

                return new Connector(driver);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return null;
            }
        }
    }
}